﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StylesheetsManager.cs" company="CodePlex">
//   The MIT License
//   Copyright (c) 2013 Julien Blin
//   
//   Permission is hereby granted, free of charge, to any person obtaining a copy
//   of this software and associated documentation files (the "Software"), to deal
//   in the Software without restriction, including without limitation the rights
//   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//   copies of the Software, and to permit persons to whom the Software is
//   furnished to do so, subject to the following conditions:
//   
//   The above copyright notice and this permission notice shall be included in
//   all copies or substantial portions of the Software.
//   
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//   THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace UCodeFirst.Stylesheets
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;

    using Umbraco.Core;
    using Umbraco.Core.Logging;

    using StylesheetProperty = umbraco.cms.businesslogic.web.StylesheetProperty;

    /// <summary>
    /// Manager responsible for synchronizing style sheet files.
    /// </summary>
    public class StylesheetsManager : UCodeFirstManagerBase
    {
        /// <summary>
        /// Suffix for CSS files that must be parsed for styles.
        /// </summary>
        private const string StylesSuffix = ".styles";

        /// <summary>
        /// The CSS property regex, used to match special properties for Umbraco.
        /// The format is the following:
        /// <code>
        /// /* $(text)$ */ (style){ (content) }
        /// </code>
        /// </summary>
        private static readonly Regex CssPropertyRegex = new Regex(@"/\*\s*\$(?<text>[^\$]+)\$\s*\*/(?<style>[^\{]+)\{(?<content>[^\}]+)\}", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.Multiline);

        /// <summary>
        /// Returns <see cref="ManagerPriorities.Stylesheets"/>.
        /// </summary>
        public override int Priority
        {
            get
            {
                return ManagerPriorities.Stylesheets;
            }
        }

        /// <summary>
        /// All the managers <see cref="UCodeFirstManagerBase.Synchronize"/> methods will run after all the managers <see cref="UCodeFirstManagerBase.BeforeSynchronization"/> method have run,
        /// <b>only</b> if the synchronization happens.<br />
        /// They run in the order specified by the <see cref="UCodeFirstManagerBase.Priority"/>.
        /// </summary>
        /// <param name="httpApplication">
        ///     The <see cref="UmbracoApplicationBase"/>.
        /// </param>
        /// <param name="applicationContext">
        ///     The <see cref="ApplicationContext"/>.
        /// </param>
        public override void Synchronize(UmbracoApplicationBase httpApplication, ApplicationContext applicationContext)
        {
            var fileService = ApplicationContext.Current.Services.FileService;
            var stylesheets = fileService.GetStylesheets().Where(x => x.Alias.EndsWith(StylesSuffix)).ToList();
            LogHelper.Debug<StylesheetsManager>(Resources.FoundNCss.InvariantFormat(stylesheets.Count));

            foreach (var stylesheet in stylesheets)
            {
                try
                {
                    LogHelper.Debug<StylesheetsManager>(Resources.Synchronizing.InvariantFormat(stylesheet.Name));

                    var targetAlias = stylesheet.Alias.Substring(0, stylesheet.Alias.Length - StylesSuffix.Length);

                    var contentWithoutProperties = stylesheet.Content;
                    var propertyMatches = CssPropertyRegex.Matches(stylesheet.Content);
                    var properties = new List<ParsedProperty>();
                    foreach (Match propertyMatch in propertyMatches)
                    {
                        properties.Add(
                           new ParsedProperty
                           {
                               Text = propertyMatch.Groups["text"].Value.Trim(),
                               Alias = propertyMatch.Groups["style"].Value.Trim(),
                               Value = propertyMatch.Groups["content"].Value.Trim(),
                           });
                        contentWithoutProperties = contentWithoutProperties.Replace(propertyMatch.Value, string.Empty);
                    }

                    var existingStyleSheet = umbraco.cms.businesslogic.web.StyleSheet.GetByName(targetAlias)
                                             ?? umbraco.cms.businesslogic.web.StyleSheet.MakeNew(
                                                 UCodeFirstConfig.GetUser(),
                                                 targetAlias,
                                                 targetAlias + ".css",
                                                 contentWithoutProperties);

                    var propertiesUpdated = false;
                    foreach (var property in properties)
                    {
                        var umbracoProperty =
                            existingStyleSheet.Properties.FirstOrDefault(x => x.Alias.InvariantEquals(property.Alias))
                            ?? existingStyleSheet.AddProperty(property.Alias, UCodeFirstConfig.GetUser());

                        var umbracoPropertyUpdater = new ConditionalPropertyUpdater<StylesheetProperty>(umbracoProperty);
                        umbracoPropertyUpdater.Update(x => x.Text, property.Text);
                        umbracoPropertyUpdater.Update(x => x.value, property.Value);
                        if (umbracoPropertyUpdater.HasBeenChanged)
                        {
                            umbracoProperty.Save();
                            propertiesUpdated = true;
                        }

                        // Delete old properties
                        var propertiesToDelete =
                            existingStyleSheet.Properties.Where(
                                x => !properties.Select(y => y.Alias).InvariantContains(x.Alias)).ToList();
                        foreach (var propertyToDelete in propertiesToDelete)
                        {
                            propertyToDelete.delete();
                            propertiesUpdated = true;
                        }
                    }

                    if (!existingStyleSheet.Content.Trim().Equals(contentWithoutProperties.Trim(), StringComparison.InvariantCultureIgnoreCase)
                        || propertiesUpdated)
                    {
                        existingStyleSheet.InvalidateCache();
                        existingStyleSheet = umbraco.cms.businesslogic.web.StyleSheet.GetByName(targetAlias);
                        existingStyleSheet.Content = contentWithoutProperties;
                        existingStyleSheet.saveCssToFile();
                    }

                    LogHelper.Debug<StylesheetsManager>(Resources.Synchronized.InvariantFormat(stylesheet.Name));
                    fileService.DeleteStylesheet(stylesheet.Name, UCodeFirstConfig.GetUser().Id);
                }
                catch (Exception ex)
                {
                    throw new UCodeFirstException(Resources.ErrorWhileSynchronizing.InvariantFormat(stylesheet.Name), ex);
                }
            }

            LogHelper.Info<StylesheetsManager>(Resources.SynchronizedNCss.InvariantFormat(stylesheets.Count));
        }

        /// <summary>
        /// A parsed property.
        /// </summary>
        private struct ParsedProperty
        {
            /// <summary>
            /// Gets or sets the text.
            /// </summary>
            public string Text { get; set; }

            /// <summary>
            /// Gets or sets the alias.
            /// </summary>
            public string Alias { get; set; }

            /// <summary>
            /// Gets or sets the value.
            /// </summary>
            public string Value { get; set; }
        }
    }
}
